#include "TestClippers.h"
#include "ParameterList.h"
#include "GenomeNTdata.h"
#include "SimSplicedRead.h"
#include "stdafx.h"
using namespace std;

const int iUpperBoundSpan = 10000;

int simSpliceRead4AGene(SimSplicedRead& sim, \
                        const char* ref, int endRefRefIndex, CGene& g,
                        int readL, int anchorL, int readNo)
{
    // int slidingWindowsNo = endRefRefIndex - g.startIndex - 2 * anchorL - sep;
    int slidingWindowsNo = 1000;
    int noSimRead = min(slidingWindowsNo, readNo - sim.noSimRead);
    sim.simulateReads(ref, g.name.c_str(), g.startIndex, noSimRead);
    return(0);
}

// This function generates the simulated spliced read that
// should all be mapped by
int simSpliceRead(const char* outFileN, CGenomeNTdata& g,\
                  int readNo, int readL, int anchorL, bool bFastaFormat)
{
    SimSplicedRead sim(outFileN);
    sim.setSimPtr(readL, anchorL, bFastaFormat);
    for (int i = 0; i < (int)g.iNo_of_chromosome; i++) {
        CchromosomeNTdata& chr = *g.paChromosomes[i];
        const char* ref = chr.caChromosome;
        if (chr.geneVec.table.size() == 0) {
            return(0); // no ref in the chr
        }
        vector<CGene>::iterator gIt = chr.geneVec.table.begin();
        vector<CGene>::iterator egIt = chr.geneVec.table.end();
        // CGene& lastGene = *(chr.geneVec.table.rbegin());
        for (; gIt != egIt; gIt++) {
            int endRefChrIndex = ((gIt + 1) == egIt) ?\
                                 chr.iChromosome_size : (gIt + 1)->startIndex;
            simSpliceRead4AGene(sim, ref, endRefChrIndex , *gIt, readL, anchorL, readNo);
            if (sim.noSimRead >= readNo) {
                return(sim.noSimRead);
            }
        }
    }
    return(sim.noSimRead);
}

int simSpliceReads(const char* outFileN, const char* genomeFileN, int readL, int anchorL)
{
    bool bFastaFormat = true;
    if (hasTheExtName(outFileN, ".fq") || hasTheExtName(outFileN, ".fastq")) {
        bFastaFormat = false;
    }
    if (hasTheExtName(genomeFileN, ".fasta" ) ||
            hasTheExtName(genomeFileN, ".fa" )) {
        CGenomeNTdata g;
        g.addChromosome(genomeFileN);
        int readNo = g.iGenomeSize - (readL + anchorL * 2) * g.iNo_of_chromosome;
        simSpliceRead(outFileN, g, readNo, readL, anchorL, bFastaFormat);
    } else if (hasTheExtName(genomeFileN, ".txt")) {
        CGenomeNTdata g(genomeFileN);
        int readNo = g.iGenomeSize - (readL + anchorL * 2) * g.iNo_of_chromosome;
        simSpliceRead(outFileN, g, readNo, readL, anchorL, bFastaFormat);
    }
    return(0);
}